package cn.fuxue.hrms.web.admin_controller;

import cn.fuxue.hrms.common.entity.User;
import cn.fuxue.hrms.service.LoginService;
import cn.fuxue.hrms.service.impl.LoginServiceImpl;
import cn.fuxue.hrms.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/login")
    public String login() {
        return "admin/login";
    }

    @PostMapping("/login")
    public String index(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpSession session,
            Model model) {

        User user= loginService.findUser(username, password);
        if(user==null) {
            return "admin/login";
        }
        user=userService.findById(user.getUserId());
        session.setAttribute("user", user);
        session.setAttribute("permissions",user.getRoles().get(0).getPermissions());
        return "redirect:/admin/index";
    }


    @GetMapping("/index")
    public String home(
            HttpSession session,
            Model model
    ) {
        return "admin/index";
    }


}
